package org.blog.controller;

import org.blog.entity.Category;
import org.blog.entity.param.CategoryParam;
import org.blog.entity.param.UpdateCategoryParam;
import org.blog.entity.vo.CategoryVO;
import org.blog.service.CategoryService;
import org.blog.utils.ResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;


    @GetMapping("admin/articleCategory")
    public ModelAndView articleCategory() {
        ModelAndView modelAndView = new ModelAndView("admin/articleCategory");

        // 根据参数获取Category
        List<CategoryVO> list = categoryService.getCategorys(new CategoryParam());

        modelAndView.addObject("list", list);
        return modelAndView;
    }

    @GetMapping("toChange/{CategoryId}")
    public void toChange(@PathVariable("CategoryId") Integer CategoryId, HttpServletRequest request, HttpServletResponse response) {

        Category category = categoryService.getCategoryById(CategoryId);
        request.setAttribute("category", category);
        try {
            request.getRequestDispatcher("/admin/articleCategoryChange.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @PostMapping("admin/change")
    @ResponseBody
    public ResultResponse change(UpdateCategoryParam param) {
        System.out.println(param);
        if (param == null) {
            return new ResultResponse(false, "参数错误");
        }
        boolean update = categoryService.update(param);
        if (update) {
            return new ResultResponse(true, "修改成功");
        } else {
            return new ResultResponse(false, "修改失败");
        }
    }

    @GetMapping("delete/{categoryId}")
    public void delete(@PathVariable("categoryId") Integer categoryId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean delete = categoryService.delete(categoryId);
        if (delete) {
            response.sendRedirect("/category/admin/articleCategory");
        } else {
            response.getWriter().println("删除失败");
            response.getWriter().close();
        }
    }


    @PostMapping("search")
    public ModelAndView search( CategoryParam param) {
        ModelAndView modelAndView = new ModelAndView("/admin/articleCategory");
        List<CategoryVO> categorys = categoryService.getCategorys(param);

        modelAndView.addObject("list", categorys);
        return modelAndView;
    }
}